<template>
	<view class="pay-main">
		<!-- 遮罩 -->
		<Shade v-if="data.lodingSwitch" />

		<view class="pay-navigation">
			<view class="navigation-content">
				<view class="back-go-btn" @click="goBack">
					<image src="@/static/back-btn.png" mode="heightFix" />
				</view>
				<view class="title">
					<text>钻石</text>
				</view>
			</view>
		</view>

		<view class="pay-body">
			<view class="balance">
				<view class="background">
					<image @click="handleBackImgClick" src="/static/balance_bcgrd.png" mode="heightFix"> </image>
				</view>
				<view class="text">
					<view class="info">
						<text>{{data.userInfo.nickName}}</text>
					</view>

					<view class="user-balance">
						<view class="title">
							<text>余额：</text>
						</view>
						<view class="price">
							<text>{{data.userInfo.balance?data.userInfo.balance/10000:0}}</text>
						</view>
						<view class="refresh-btn">
							<image src="/static/refresh.png" mode="heightFix"> </image>
						</view>
					</view>
				</view>
				<!-- 刷新余额 -->
				<view class="refresh" @click="doRefreshBalance">

				</view>
			</view>
			<!-- 商品列表 -->
			<view class="product-view">
				<view class="p-item" :class="{'selected':item.id==data.selectedItem.id}"
					v-for="(item,index) in data.dataList" @click="doSelect(item)">
					<view class="num-text">{{item.originalPrice/10000}}钻石</view>
					<view class="price-text">￥{{item.discountPrice/10000}}</view>
				</view>

				<!-- 伪元素 -->
				<view class="after" v-if="data.dataList.length%3>0">
				</view>
			</view>

			<!-- 立即充值按钮 -->
			<view class="pay-btn" @click="doPayClick">
				<button>立即充值</button>
			</view>

			<!-- 支付协议 -->
			<view class="pay-protocol">
				<view :class="data.protocolChecked?'checkbox checked':'checkbox'">
					<checkbox color="#ffffff" :checked="data.protocolChecked" @click="doCheck"></checkbox>
				</view>
				<view class="text">
					<text>支付即表示同意</text>
					<navigator url="../pay-protocol" hover-class="navigator-hover">
						<text style="color: #269BF8;">《火箭体育充值协议》</text>
					</navigator>
				</view>
			</view>

			<!-- 支付提示 -->
			<view class="pay-tips">
				<view class="pay-tips-text">
					<text>
						温馨提示：\n1. 火箭体育非购彩平台，钻石只可用于购买模型数据，不支持购彩、退款、提现等操作。\n2. 充值可能会延迟到账问题，请耐心等待。\n3. 如在钻石充值或消费过程中遇到问题，请及时联系客服！点击联系 在线客服！
					</text>
				</view>
			</view>
		</view>

		<!-- 遮罩 -->
		<view class="pay-shad" v-if="data.shadSwitch"></view>

		<view class="pay-detail" v-if="data.payDetailSwitch">
			<view class="pay-detail-body">
				<view class="close" @click="doClosePay">
					<image src="@/static/close_btn.png" mode="heightFix"></image>
				</view>
				<view class="real-amount">
					<text>实付金额</text>
				</view>
				<view class="user-amount">
					<text class="symbol">￥</text>
					<text class="value">{{data.selectedItem.discountPrice/10000}}</text>
				</view>
				<view class="amount-tips">
					<text>本次充值{{data.selectedItem.originalPrice/10000}}钻石，需要支付{{data.selectedItem.discountPrice/10000}}元</text>
				</view>

				<!-- 支付渠道 -->
				<view class="pay-channel">
					<radio-group @change="radioChange">
						<view class="channel-detail" v-for="(item,index) in data.payChannelList">
							<view class="p-icon">
								<image
									:src="item.payChannelType==4?'/static/icon_recharge_alipay.png':item.payChannelType==5?'/static/icon_recharge_wechat.png':''"
									mode="heightFix">
								</image>
							</view>
							<view class="p-name">
								{{item.channelName}}
							</view>
							<view class="p-checkbox">
								<radio :value="String(item.payChannelType)"
									:checked="item.payChannelType==data.selectedChannel.payChannelType"></radio>
							</view>
						</view>
					</radio-group>
				</view>

				<view class="save-btn" @click="doSubmitPay">
					<button :loading="data.confirmDisabled" :disabled="data.confirmDisabled">确定</button>
				</view>
			</view>
		</view>

		<alipayVue :form-data="data.aliPayformData"  v-if="data.showAlipay"></alipayVue>
	</view>
</template>

<script setup>
	import {
		reactive,
		onMounted,
		getCurrentInstance,
		nextTick,
		onUnmounted,
		computed,
	} from 'vue';
	import {
		AUTH_TOKEN_KEY,
		ORIGIN_HEADER,
		toast
	} from '@/api/utils/common';
	import {
		getUserInfo,
		getProductList,
		getChannelList,
		createPayOrder
	} from '@/api/pay.js';
	import {
		decrypt,
		encrypt
	} from '@/api/utils/secret.js'
	import md5 from 'md5';
	import { differenceInMinutes } from 'date-fns';
	import alipayVue from '../../components/alipay.vue';
	import Shade from '@/components/shade.vue'
	const redirectUrl = computed(() => {
		let base = window.location.origin;
		let dataUrl = "?data=";
		let header = uni.getStorageSync(ORIGIN_HEADER);
		let token = uni.getStorageSync(AUTH_TOKEN_KEY);
		let params = {
			header: header,
			token: token
		}
		let secretCode = encrypt(JSON.stringify(params));
		let pathCode = encodeURIComponent(secretCode);
		return base + dataUrl + pathCode;
	});

	const data = reactive({
		lodingSwitch: false,
		userInfo: {},
		showProtocol: false,
		shadSwitch: false,
		payDetailSwitch: false,
		dataList: [],
		protocolChecked: false,
		selectedItem: {},
		token: "",
		payChannelList: [

		],
		selectedChannel: {

		},
		aliPayformData: "",
		showAlipay: false,
		confirmDisabled: false
	})
	onMounted(() => {
		doClosePay();
		console.log(redirectUrl.value)
		const instance = getCurrentInstance().proxy;
		let params = instance.options.data;
		if (!params) {
			//回退页面
			goBack();
			toast("参数错误")
			return;
		}
		/*解密数据 {
			header: {},
			token: ''
		}*/
		let decryptStr = decrypt(params);
		let decodeData = JSON.parse(decryptStr);

		//将token缓存在本地
		uni.setStorageSync(AUTH_TOKEN_KEY,decodeData.token)

		//缓存请求头
		uni.setStorageSync(ORIGIN_HEADER, decodeData.header)

		//获取商品信息
		doGetProductList();

		//计算是否过期
		let expired = isExpired(decodeData.header.ts);
		if (expired) {
			return;
		}

		// //获取用户信息
		doGetUserInfo()

	})

	const isExpired = (ts) => {
		if (!ts) {
			uni.removeStorageSync(AUTH_TOKEN_KEY);
			data.userInfo = {}
			return true;
		}
		let startTime = new Date(ts);
		let endTime = new Date();
		let minutesDiff = differenceInMinutes(endTime, startTime);

		// 判断是否在15分钟以内
		if (minutesDiff > 15) {
			uni.removeStorageSync(AUTH_TOKEN_KEY);
			data.userInfo = {}
			return true;
		}

		return false;
	}


	// 获取商品列表
	const doGetProductList = () => {

		getProductList(3).then(resp => {
			if (!resp || resp.length <= 0) {
				toast("没有可支付的金额")
				return;
			}
			data.dataList = resp;
			data.selectedItem = resp[0];
		})
	}


	const doGetUserInfo = () => {
		getUserInfo().then(resp => {
			data.userInfo = resp;
		})
	}

	const goBack = () => {
		// 判断当前是否在H5页面
		if (window.location.href.indexOf('your-h5-url-pattern') !== -1) {
			// 执行回退到App的操作
			window.location.href = 'app-scheme://goBack'; // 替换为实际回到App的URL或逻辑
		} else {
			history.back();
		}

	}

	//选择
	const doSelect = (item) => {
		data.selectedItem = item;
	}

	const doCheck = () => {
		data.protocolChecked = !data.protocolChecked
	}

	const radioChange = (e) => {
		for (let i = 0; i < data.payChannelList.length; i++) {
			if (data.payChannelList[i].payChannelType === Number(e.detail.value)) {
				data.selectedChannel = data.payChannelList[i];
				break;
			}
		}
	}

	const doClosePay = () => {
		data.shadSwitch = false;
		data.payDetailSwitch = false;
		data.showAlipay=false;
	}

	//立即充值
	const doPayClick = () => {
		if (!data.protocolChecked) {
			toast("请阅读并勾选充值协议")
			return false;
		}

		if (!data.userInfo.id) {
			toast("请先登录")
			return false;
		}

		//定义请求参数
		let param = {
			userIdStr: md5(data.userInfo.id),
			amount: data.selectedItem.discountPrice
		}


		//查询支付渠道
		getChannelList(param).then(resp => {
			if (!resp || resp.length <= 0) {
				toast("没有可支付的渠道")
				return;
			}
			data.payChannelList = resp;
			data.selectedChannel = resp[0];
		})


		data.shadSwitch = true;
		//获取支付渠道
		data.payDetailSwitch = true;
	}

	//提交支付申请
	const doSubmitPay = async () => {
		data.confirmDisabled = true;
		try {
			//获取用户信息
			let userIdMd5Str = md5(data.userInfo.id) + randomTwoNumber();
			let productCode = data.selectedItem.productCode
			let payChannelType = data.selectedChannel.payChannelType

			//组装支付参数
			let param = {
				randomStr: userIdMd5Str, //用户MD5 userId
				productCode: productCode, //商品id
				payChannelType: payChannelType, //支付渠道
				amountType: 3, //币种类型
				orderMoney: data.selectedItem.discountPrice
			}

			//发起支付请求
			await createPayOrder(param).then(resp => {
				if (payChannelType == 4) { //支付宝
					data.aliPayformData = resp.body;
					data.showAlipay = true;
					
				} else if (payChannelType == 5) { //微信
					console.log(redirectUrl.value);
					window.location.href = resp.body + "&redirect_url=" + encodeURIComponent(redirectUrl.value);
				}

			})
		} catch (error) {

		} finally {
			data.confirmDisabled = false;
			doClosePay();
		}

	}

	//随机生成两位数
	const randomTwoNumber = () => {
		// 生成一个0到99之间的随机数
		let randomNum = Math.floor(Math.random() * 100);
		// 确保结果是两位数，不足两位前面补0
		return String(randomNum).padStart(2, '0');
	}


	const handleBackImgClick = (e) => {
		e.preventDefault();
		e.stopPropagation();
		toast("点击背景图")
	}

	let shadeTimer = null;
	const doRefreshBalance = async () => {
		data.lodingSwitch = true;
		try {
			await doGetUserInfo();
		} catch (error) {
			console.log(error);
		} finally {
			shadeTimer = setTimeout(() => {
				data.lodingSwitch = false;
			}, 1500);
		}
	}

	onUnmounted(() => {
		if (shadeTimer) {
			clearTimeout(shadeTimer);
		}
	})
</script>

<style lang="scss" scoped>
	.pay-main {

		display: flex;
		flex-direction: column;
		align-items: center;
		background-color: #EFF2F7;
		height: 100%;
		width: 100%;
		position: fixed;
		font-family: 'PingFang SC';

		.pay-detail {
			width: 100%;
			height: 438px;
			z-index: 999;
			position: absolute;
			bottom: 0px;
			background: #FAFAFA;
			box-shadow: 0 0 3px 3px rgba(0, 0, 0, 0.1);
			display: flex;
			justify-content: center;
			border-radius: 8px 8px 0px 0px;

			.pay-detail-body {
				display: flex;
				flex-direction: column;
				width: 345px;
				align-items: center;
				height: 99%;

				.close {
					width: 100%;
					height: 18px;
					margin-top: 10px;
					display: flex;
					justify-content: end;

					uni-image {
						height: 18px;
					}
				}

				.real-amount {
					height: 22px;
					font-size: 14px;
					font-weight: 400;
					line-height: 22px;
					color: #999999;
				}

				.user-amount {
					height: 36px;
					margin-top: 20px;
					color: #FF0000;
					display: flex;
					align-items: center;

					.symbol {
						font-size: 24px;
					}

					.value {
						font-size: 36px;
					}
				}

				.amount-tips {
					margin-top: 20px;
					font-size: 12px;
					color: #999999;
					line-height: 22px;
					height: 22px;
				}


				.pay-channel {
					display: flex;
					flex-direction: column;
					flex-grow: 1;
					overflow-y: auto;
					width: 100%;
					overflow-x: hidden;

					.channel-detail {
						width: 100%;
						height: 50px;
						display: flex;
						flex-direction: row;
						align-items: center;
						background-color: #FFFFFF;
						box-shadow: 0 -0.5px 0 0 #F0F0F0;

						.p-icon {
							height: 24px;
							margin-left: 15px;

							uni-image {
								height: 24px;
							}
						}

						.p-name {
							margin-left: 8px;
							width: 100px;
						}

						.p-checkbox {
							display: flex;
							align-items: center;
							justify-content: end;
							grid-row: 1;
							width: 100%;
							margin-right: 10px;

							uni-radio {
								display: flex;
								justify-content: center;
								align-items: center;
							}

							::v-deep .uni-radio-input {
								width: 18px;
								height: 18px;
							}
						}
					}


				}

				.save-btn {
					width: 296px;
					height: 45px;
					border-radius: 22.5px;
					overflow: hidden;
					background: linear-gradient(to bottom, #4EDCFE, #309EFD, #309EFD, #4EDCFE);
					margin: 39px 0;

					::v-deep uni-button {
						background-color: transparent !important;
						color: #fff;
					}
				}
			}
		}


		.pay-shad {
			height: 100%;
			width: 100%;
			z-index: 995;
			background-color: #00000099;
			position: absolute;
		}

		.pay-navigation {
			position: absolute;
			height: 68px;
			width: 100%;
			box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.1);
			border-radius: 0px 0px 16px 16px;
			background-color: #ffffff;

			.navigation-content {
				height: 25px;
				display: flex;
				flex-direction: row;
				width: 100%;
				justify-content: center;
				position: absolute;
				bottom: 10px;
				line-height: 25px;

				.back-go-btn {
					height: 15px;
					width: 7.5px;
					position: absolute;
					left: 17.5px;

					uni-image {
						height: 15px;
					}
				}

				.title {
					font-family: 'PingFang SC';
					font-weight: 700;
					font-size: 18px;
					letter-spacing: 1.2px;
					color: #222222;
				}
			}
		}

		.pay-body {
			position: absolute;
			top: 68px;
			width: 345px;
			flex-grow: 1;
			display: flex;
			flex-direction: column;
			align-items: center;
			overflow-y: scroll;
			overflow-x: hidden;
			bottom: 10px;

			.balance {
				width: 100%;
				height: 88px;
				display: flex;
				align-items: center;
				//position: absolute;
				margin-top: 10px;
				position: relative;

				.refresh {
					position: absolute;
					width: 100%;
					height: 100%;
				}

				.background {
					width: 100%;
					height: 100%;

					uni-image {
						height: 88px;
					}
				}

				.text {
					//z-index: 996;
					color: #ffffff;
					position: absolute;
					height: 75px;
					width: 250px;
					margin-left: 20px;
					display: flex;
					flex-direction: column;
					justify-content: left;
					align-items: left;

					.info {
						font-size: 14px;
						font-weight: 700;
						display: flex;
						justify-content: left;
						align-items: center;
						margin-top: 5px;
					}

					.user-balance {
						display: flex;
						flex-direction: row;
						width: 250px;
						//margin-top: 20px;
						overflow: hidden;
						height: 65px;

						.price {
							font-family: '阿里巴巴普惠体';
							font-size: 24px;
							font-weight: 400;
							line-height: 33px;
							display: flex;
							align-items: center;
						}

						.refresh-btn {
							//height: 40px;
							margin-left: 5px;
							display: flex;
							justify-content: center;
							align-items: center;

							uni-image {
								height: 15px;
							}
						}
					}

					.title {
						font-size: 14px;
						line-height: 25px;
						font-weight: 400;
						display: flex;
						align-items: center;
					}
				}
			}

			.product-view {
				display: flex;
				flex-direction: row;
				flex-wrap: wrap;
				width: 100%;
				justify-content: space-between;

				.p-item {
					//flex-grow: 1;
					height: 60px;
					width: 105px;
					background-color: #ffffff;
					border-radius: 5px;
					margin: 10px 0px 0px 0px;
					display: flex;
					justify-content: center;
					flex-direction: column;
					align-items: center;

					/* 让子项目可以扩展 */
					.num-text {
						font-family: 'PingFang SC';
						font-weight: 400;
						font-size: 15px;
						color: #222222;
					}

					.price-text {
						font-family: 'PingFang SC';
						font-weight: 400;
						font-size: 12px;
						color: #999999;
					}
				}

				.selected {
					background-color: #269BF8;

					.num-text {
						color: #FFFFFF !important;
					}

					.price-text {
						color: #FFFFFF !important;
					}

				}

				.after {
					content: '';
					height: 60px;
					width: 105px;
					//background-color: #ffffff;
					border-radius: 5px;
					margin: 10px 0px 0px 0px;
					display: flex;
					justify-content: center;
					flex-direction: column;
					align-items: center;
					//	flex: auto;
					/* 填充剩余空间 */
				}
			}

			.pay-btn {
				width: 296px;
				height: 45px;
				margin-top: 20px;
				border-radius: 22.5px;

				uni-button {
					color: #ffffff;
					border-radius: 22.5px;
					background: linear-gradient(to bottom, #4EDCFE, #309EFD, #309EFD, #4CC1FF);
					font-family: 'PingFang SC';
					font-size: 16px;
					letter-spacing: 1.2px;
				}
			}

			.pay-protocol {
				height: 17px;
				width: 100%;
				margin-top: 14px;
				display: flex;
				flex-direction: row;
				justify-content: center;
				align-items: center;

				.checkbox {
					::v-deep uni-checkbox {
						width: 14px;
						height: 14px;
						display: flex;
						justify-content: center;
						align-items: center;

						.uni-checkbox-input {
							width: 14px;
							height: 14px;
							margin-right: 0;
							background-color: #FFFFFF;
						}
					}
				}

				.checked {
					::v-deep uni-checkbox {
						color: #ffffff;

						.uni-checkbox-input {
							background-color: #269BF8;
							color: #ffffff;
						}
					}
				}

				.text {
					font-family: 'PingFang SC';
					font-size: 12px;
					color: #999999;
					margin-left: 10px;
					display: flex;
					flex-direction: row;
				}
			}

			.pay-tips {
				margin-top: 10px;
				height: 254px;
				width: 100%;
				background: #ffffff;
				border-radius: 10px;
				display: flex;
				justify-content: center;
				align-items: center;

				.pay-tips-text {
					height: 231px;
					width: 316px;
					font-size: 12px;
					line-height: 19px;
					letter-spacing: 0.72px;
					color: #222222;
					display: flex;
					align-items: center;
				}

			}
		}
	}
</style>